package com.example.g7640.controller;

import com.example.g7640.dto.LoginDto;
import com.example.g7640.dto.RegistDto;
import com.example.g7640.dto.SessionDto;
import com.example.g7640.dto.UserChangePasswordDto;
import com.example.g7640.exception.BizException;
import com.example.g7640.dto.common.Result;
import com.example.g7640.service.UserService;
import com.example.g7640.builder.ResultBuilder;
import com.example.g7640.util.PasswordUtil;
import com.example.g7640.util.SessionLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/common")
public class UserController {

    @Autowired
    List<UserService> userServiceList;

    Map<Integer, UserService> userServiceMap;


    private UserService getUserService(Integer type) {
        if (userServiceMap == null) {
            userServiceMap = userServiceList.stream().collect(Collectors.toMap(e -> e.getType(), e -> e));
        }
        return userServiceMap.get(type);
    }

    @PostMapping("/reg")
    public Result<String> register(@RequestBody RegistDto registDto) {
        if (registDto == null) {
            throw new BizException("Please input message");
        }

        String password = PasswordUtil.encodePassword(registDto.getPassword());
        registDto.setPassword(password);

        getUserService(registDto.getType()).register(registDto);
        return ResultBuilder.buildSuccess(null);
    }

    @PostMapping("/login")
    public Result<String> login(@RequestBody LoginDto loginDto, HttpServletRequest request) {
        String password = PasswordUtil.encodePassword(loginDto.getPassword());
        loginDto.setPassword(password);
        SessionDto sessionDto = getUserService(loginDto.getType()).login(loginDto);
        request.getSession().setAttribute(SessionLocal.SESSION, sessionDto);
        return ResultBuilder.buildSuccess(null);
    }


    @GetMapping("/loginInfo")
    public Result<SessionDto> loginInfo(HttpServletRequest request){
        HttpSession session = request.getSession();
        SessionDto sessionDto = (SessionDto) session.getAttribute(SessionLocal.SESSION);
        return ResultBuilder.buildSuccess(sessionDto);
    }



    @GetMapping("/logout")
    public Result<String> logout(HttpServletRequest request){
        HttpSession session = request.getSession();
        if(session != null){
            session.removeAttribute(SessionLocal.SESSION);
        }
        return ResultBuilder.buildSuccess();
    }

    @PostMapping("/change-password")
    public Result<SessionDto> changePassword(@RequestBody UserChangePasswordDto u){
        System.out.println("userType: " + u.getType());
        getUserService(u.getType()).changePassword(u);
        return ResultBuilder.buildSuccess(null);
    }
}
